package com.team11.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.team11.server.config.SplicingConfig;
import com.team11.server.pojo.dto.*;
import com.team11.server.pojo.dto.vo.AddWorkListVo;
import com.team11.server.mapper.*;
import com.team11.server.pojo.*;
import com.team11.server.pojo.dto.vo.JobAuditListVo;
import com.team11.server.service.IHInformationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.team11.server.util.file.GetFilesUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author pjc
 * @since 2021-06-17
 */
@Service
public class HInformationServiceImpl extends ServiceImpl<HInformationMapper, HInformation> implements IHInformationService {

    @Resource
    private HInformationMapper hInformationMapper;

    @Resource
    private HomeworkMapper homeworkMapper;

    @Resource
    private PInformationMapper pInformationMapper;

    @Resource
    private CFilesMapper cFilesMapper;

    @Resource
    private TInformationMapper tInformationMapper;

    @Resource
    private KcInformationMapper kcInformationMapper;


    /**
     * 获取下发的作业列表
     *
     * @param currentPage   当前页
     * @param size          条数
     * @param addWorkListVo 查询参数
     * @return list
     */
    @Override
    public RespPageBean getDistributeJobList(Integer currentPage, Integer size, AddWorkListVo addWorkListVo) {
        List<Integer> list = new ArrayList<>();

        IPage<AddWorkList> page = new Page<>(currentPage, size);
        IPage<AddWorkList> distributeJobList = hInformationMapper.getDistributeJobList(page, addWorkListVo);
        try {
            for (int i = 0; i < distributeJobList.getTotal(); i++) {
                Integer hId = distributeJobList.getRecords().get(i).getHId();
                list.add(hId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("异常");
        }
        for (int i = 0; i < list.size(); i++) {
            //获取需提交作业学生总数，并装入data
            distributeJobList.getRecords().get(i).setNum(homeworkMapper.getNumByHId(list.get(i)));
            //获取待提交作业学生总数，并装入data
            distributeJobList.getRecords().get(i).setNum1(homeworkMapper.getNum1ByStatus(list.get(i)));
            //获取待批复作业学生总数，并装入data
            distributeJobList.getRecords().get(i).setNum2(homeworkMapper.getNum2ByStatus(list.get(i)));
            //获取已批复作业学生总数，并装入data
            distributeJobList.getRecords().get(i).setNum3(homeworkMapper.getNum3ByStatus(list.get(i)));
        }
        return new RespPageBean(distributeJobList.getTotal(), distributeJobList.getRecords());
    }


    /**
     * 下发（新增）作业
     *
     * @param addHomeWork 新增参数
     * @return respBean
     */


    @Override
    public RespBean addHomework(AddHomeWork addHomeWork, List<Integer> pId, List<String> student, String tJobNumber,
                                MultipartFile[] files, HttpServletRequest request) {

        if (student.size() == 0 || pId.size() == 0) {
            return RespBean.error("小组或者学员不能为空!");
        }

        HInformation hInformation = new HInformation();
        hInformation.setHStoptime(addHomeWork.getHStoptime());
        hInformation.setHType(addHomeWork.getHType());
        hInformation.setHTitle(addHomeWork.getHTitle());
        hInformation.setKcId(addHomeWork.getKcId());
        hInformation.setSContent(addHomeWork.getSContent());

        Integer tId = tInformationMapper.selectOne(new QueryWrapper<TInformation>()
                .eq("t_job_number", tJobNumber)).getTId();
        hInformation.setTId(tId);
        //获取发布时间
        hInformation.setHSetime(LocalDateTime.now(Clock.system(ZoneId.of("Asia/Shanghai"))));

        //获取发布作业的接收者（小组名称）
        List<String> list = new ArrayList<>();
        for (int i = 0; i < pId.size(); i++) {
            list.add(i, pInformationMapper.selectOne(new QueryWrapper<PInformation>().eq("p_id", pId.get(i))).getPName());
        }
        hInformation.setReceiver(SplicingConfig.Splicing(list));

        //附件
        CFiles cFiles = new CFiles();
        List<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        //上传文件，并保存路径到数据库
        if (files != null) {
            List<String> list3 = GetFilesUtil.getFiles(files, request);
            list1.add(list3.get(0));
            list2.add(list3.get(1));
            hInformation.setReceiver(SplicingConfig.Splicing(list));
            cFiles.setCFName(SplicingConfig.Splicing(list1));
            cFiles.setCFile(SplicingConfig.Splicing(list2));
        }

        //发布作业
        if (1 == hInformationMapper.insert(hInformation)) {
            //上传附件信息到数据库
            if (files != null) {
                cFiles.setCFType(0);
                cFiles.setTId(tId);
                cFiles.setHId(hInformation.getHId());

                if (cFilesMapper.insert(cFiles) == 1) {
                    hInformation.setCFId(cFiles.getCFId());
                    hInformationMapper.updateById(hInformation);
                }
            }
            //下发作业给学生
            Homework homework = new Homework();
            for (String s : student) {
                homework.setHId(hInformation.getHId());
                homework.setStatus(0);

                String[] a = s.split(":");
                int sid = Integer.parseInt(a[0]);
                Integer pId1 = Integer.valueOf(a[1]);
                if (homeworkMapper.selectCount(new QueryWrapper<Homework>()
                        .eq("sid", sid).eq("h_id", hInformation.getHId())) != 0) {
                    continue;
                }
                homework.setPId(pId1);
                homework.setSid(sid);
                homeworkMapper.insert(homework);

            }
            return RespBean.success("下发作业成功！");
        }
        return RespBean.error("下发失败!");
    }


    /**
     * 教师删除作业
     *
     * @param hId 作业id
     * @return RespBean
     */
    @Override
    public RespBean deleteWork(Integer hId) {
        try {

            Integer cFId = hInformationMapper.selectOne(new QueryWrapper<HInformation>().eq("h_id", hId)).getCFId();
            if (cFId != null) {
                cFilesMapper.deleteById(cFId);
            }

            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("h_id", hId);
            List<Homework> list = homeworkMapper.selectByMap(columnMap);
            if (list.size() != 0) {
                homeworkMapper.deleteByMap(columnMap);
            }

            hInformationMapper.deleteById(hId);

            return RespBean.success("删除成功!");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("删除失败!");
    }

    /**
     * 根据Hid获取作业信息
     *
     * @param hId 作业id
     * @return List
     */

    @Override
    public List<Object> getWorkByHId(Integer hId) {
        List<Object> list = new ArrayList<>();

        try {
            //获取作业信息
            HInformation hInformation = hInformationMapper.selectOne(new QueryWrapper<HInformation>().eq("h_id", hId));
            list.add(hInformation);

            //附件地址

            if (hInformation.getCFId() != null) {
                Map<String, Object> map = new HashMap<>();
                CFiles cFiles = cFilesMapper.selectOne(new QueryWrapper<CFiles>().eq("c_f_id", hInformation.getCFId()));
                map.put("cFId", cFiles.getCFId());
                map.put("cFile", cFiles.getCFile());
                map.put("cFName", cFiles.getCFName());
            }

            //获取课程
            String kcName = kcInformationMapper.selectOne(new QueryWrapper<KcInformation>().eq("kc_id", hInformation.getKcId())).getKcName();
            List<Object> list3= new ArrayList<>();
            Map<String, Object> map1 = new HashMap<>();
            map1.put("kcName", kcName);
            map1.put("kcId", hInformation.getKcId());
            list3.add(map1);
            list.add(list3);

            //小组
            List<Homework> list1 = homeworkMapper.selectList(new QueryWrapper<Homework>().eq("h_id", hId));
            List<Object> list2 = new ArrayList<>();
            for (Homework homework : list1) {
                String pName = pInformationMapper.selectOne(new QueryWrapper<PInformation>().eq("p_id", homework.getPId())).getPName();
                Map<String, Object> map2 = new HashMap<>();
                map2.put("pName", pName);
                map2.put("pId", homework.getPId());
                list2.add(map2);
            }
            list.add(list2);

            //获取学生
            List<Map<String, Object>> list4 =hInformationMapper.getSIdJoinPId(hId);
            list.add(list4);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 教师修改作业
     *
     * @param addHomeWork s
     * @param pId         s
     * @param student     s
     * @param files       s
     * @param request     s
     * @return RespBean
     */
    @Override
    public RespBean updateWork(AddHomeWork addHomeWork, List<Integer> pId,
                               List<String> student, String tJobNumber, Integer hId, MultipartFile[] files, HttpServletRequest request) {
        if (student.size() == 0 || pId.size() == 0) {
            return RespBean.error("小组或者学员不能为空!");
        }

        System.out.println(student);
        HInformation hInformation = new HInformation();
        Integer tId = tInformationMapper.selectOne(new QueryWrapper<TInformation>()
                .eq("t_job_number", tJobNumber)).getTId();
        if (!tId.equals(hInformationMapper.selectOne(new QueryWrapper<HInformation>().eq("h_id", hId)).getTId())) {
            return RespBean.error("您没有权限修改此作业!");
        }
        hInformation.setTId(tId);
        hInformation.setHStoptime(addHomeWork.getHStoptime());
        hInformation.setHType(addHomeWork.getHType());
        hInformation.setHTitle(addHomeWork.getHTitle());
        hInformation.setKcId(addHomeWork.getKcId());
        hInformation.setSContent(addHomeWork.getSContent());
        hInformation.setHId(hId);


        //获取发布接收者（小组名称）
        List<String> list = new ArrayList<>();
        for (int i = 0; i < pId.size(); i++) {
            list.add(i, pInformationMapper.selectOne(new QueryWrapper<PInformation>().eq("p_id", pId.get(i))).getPName());
        }
        hInformation.setReceiver(SplicingConfig.Splicing(list));

        //附件
        CFiles cFiles = new CFiles();
        List<String> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();

        if (1 == hInformationMapper.updateById(hInformation)) {
            //附件
            if (files != null) {
                List<String> list3 = GetFilesUtil.getFiles(files, request);
                list1.add(list3.get(0));
                list2.add(list3.get(1));
                cFiles.setCFName(SplicingConfig.Splicing(list1));
                cFiles.setCFile(SplicingConfig.Splicing(list2));
                //保存到数据库代码，存入路径以及文件名称
                cFiles.setTId(tId);
                cFiles.setHId(hId);
                cFiles.setCFType(0);


                //判断hInformation中有没有c_f_id
                if (hInformationMapper.selectOne(new QueryWrapper<HInformation>().eq("h_id", hId)).getCFId() != null) {
                    Integer hCFId = hInformationMapper.selectOne(new QueryWrapper<HInformation>().eq("h_id", hId)).getCFId();
                    CFiles cFiles1 = cFilesMapper.selectOne(new QueryWrapper<CFiles>().eq("c_f_id", hCFId));
                    if (cFiles1 != null) {
                        cFiles.setCFId(hCFId);
                        cFilesMapper.updateById(cFiles);
                    } else {
                        hInformationMapper.SetCFIdNull(hId);
                        cFilesMapper.insert(cFiles);
                        hInformation.setCFId(cFiles.getCFId());
                        hInformationMapper.updateById(hInformation);
                    }

                } else {
                    if (cFilesMapper.insert(cFiles) == 1) {
                        hInformation.setCFId(cFiles.getCFId());
                        hInformationMapper.updateById(hInformation);
                    }
                }


            } else {
                Integer cFId = hInformationMapper.selectOne(new QueryWrapper<HInformation>().eq("h_id", hId)).getCFId();
                if (cFId != null) {
                    cFilesMapper.deleteById(cFId);
                    hInformationMapper.SetCFIdNull(hId);
                }
            }

            //获取该作业下的学生id
            List<Homework> items = homeworkMapper.selectList(new QueryWrapper<Homework>().eq("h_id", hId));
            List<Integer> list4 = items.stream().map(Homework::getSid).collect(Collectors.toList());

            if (list4.size() != 0) {
                //如果该作业下有学生
                //处理：修改后的学生和数据库中已经有的学生比较过后，如修改后有新增，新增该作业下的学生
                for (int i = 0; i < student.size(); i++) {
                    int count = 0;
                    for (int j = 0; j < list4.size(); j++) {

                        String[] a = student.get(i).split(":");
                        System.out.println(student);
                        int sid = Integer.parseInt(a[0]);
                        Integer pId1 = Integer.valueOf(a[1]);

                        if (sid != list4.get(j)) {
                            count++;
                            if (count >= list4.size()) {
                                Homework homework = new Homework();
                                homework.setHId(hId);
                                homework.setStatus(0);
                                homework.setPId(pId1);
                                homework.setSid(sid);
                                homeworkMapper.insert(homework);
                            }
                        }
                    }
                }

                //获取新增过后的学生id
                List<Homework> items1 = homeworkMapper.selectList(new QueryWrapper<Homework>().eq("h_id", hId));
                List<Integer> list5 = items1.stream().map(Homework::getSid).collect(Collectors.toList());
                //处理：修改后的学生和数据库中已经有的学生比较过后，如修改后有删减，则删除数据库中减少的学生
                for (Integer integer : list5) {
                    int count = 0;
                    for (int j = 0; j < student.size(); j++) {

                        String[] a = student.get(j).split(":");
                        Integer sid = Integer.valueOf(a[0]);

                        if (!integer.equals(sid)) {
                            count++;
                            if (count >= student.size()) {
                                Map<String, Object> map = new HashMap<>();
                                map.put("h_id", hId);
                                map.put("sid", integer);
                                homeworkMapper.deleteByMap(map);
                            }
                        }
                    }
                }
            } else {
                //如果改作业下没有学生，则进行新增
                for (String s : student) {
                    String[] a = s.split(":");
                    Integer sid = Integer.valueOf(a[0]);
                    Integer pId1 = Integer.valueOf(a[1]);

                    if (homeworkMapper.selectCount(new QueryWrapper<Homework>()
                            .eq("sid", sid).eq("h_id", hId)) != 0) {
                        continue;
                    }
                    Homework homework1 = new Homework();
                    homework1.setHId(hId);
                    homework1.setStatus(0);
                    homework1.setPId(pId1);
                    homework1.setSid(sid);
                    homeworkMapper.insert(homework1);
                }
            }

            return RespBean.success("修改作业成功！");
        }
        return RespBean.error("修改作业失败!");
    }

    /**
     * 审核作业列表
     *
     * @param currentPage 当前页
     * @param size        条数
     * @return RespPageBean
     */
    @Override
    public RespPageBean getJobAuditList(Integer currentPage, Integer size, Integer status, JobAuditListVo jobAuditListVo) {
        IPage<JobAuditList> page = new Page<>(currentPage, size);
        IPage<JobAuditList> jobAuditList1 = hInformationMapper.getJobAuditList(page, status, jobAuditListVo);
        return new RespPageBean(jobAuditList1.getTotal(), jobAuditList1.getRecords());
    }

    /**
     * 获取作业任务列表
     *
     * @param hId 作业id
     * @return WorkTask
     */
    @Override
    public WorkTask getWorkTask(Integer hId) {
        WorkTask workTask = new WorkTask();

        try {
            HInformation hInformation = hInformationMapper.selectOne(new QueryWrapper<HInformation>().eq("h_id", hId));
            workTask.setHTitle(hInformation.getHTitle());
            workTask.setHSetime(hInformation.getHSetime());
            workTask.setHStoptime(hInformation.getHStoptime());
            workTask.setSContent(hInformation.getSContent());

            CFiles cFiles = cFilesMapper.selectOne(new QueryWrapper<CFiles>().eq("c_f_id", hInformation.getCFId()));
            workTask.setCFile(cFiles.getCFile());
            workTask.setCFName(cFiles.getCFName());
            workTask.setCFId(cFiles.getCFId());

            TInformation tInformation = tInformationMapper.selectOne(new QueryWrapper<TInformation>().eq("t_id", hInformation.getTId()));
            workTask.setTName(tInformation.getTName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return workTask;
    }


}
